<?php

namespace App\Http\Controllers\Frontend;

use App\Exceptions\ValidateException;
use App\Http\Controllers\Controller;
use App\Repository\Contracts\CodeInterface;
use App\Repository\Contracts\UserInterface;
use App\Support\Helper\CommonHelper;
use Illuminate\Http\Request;
use Auth;

/**
 * @Author:: HuangYin
 * @DateTime: 2017/6/7 22:35
 */
class UserController extends Controller
{
    /**
     * @var Request
     */
    protected $request;

    /**
     * @var UserInterface
     */
    protected $user;

    /**
     * @var CodeInterface
     */
    protected $code;

    /**
     * @var int
     */
    protected $uid;

    /**
     * UserController constructor.
     *
     * @param Request $request
     * @param UserInterface $user
     * @param CodeInterface $code
     */
    public function __construct(Request $request, UserInterface $user, CodeInterface $code)
    {
        $this->request = $request;

        $this->user = $user;

        $this->code = $code;

        $this->uid = CommonHelper::getToken(Auth::user())['uid'] ?: 0;
    }

    /**
     * 登录
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function login()
    {
        try {
            $data['phone'] = $this->request->input('phone', null);
            $code = $this->request->input('code', null);
            if (!$codeData = $this->code->checked($data['phone'], $code)) {

                return $this->fail('验证码无效');
            }
            $this->code->updateStatus($codeData->id);
            $user = $this->user->login($data);

            return $this->success($user);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * 详情
     *
     * @param $id
     * @return \Illuminate\Http\JsonResponse
     */
    public function detail($id)
    {
        $detail = $this->user->detail($id);

        return $this->success($detail);
    }

    /**
     * 更新资料
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function update()
    {
        try {
            $data = $this->request->only([
                'nickname', 'sex', 'province_id', 'subject', 'score', 'real_name', 'student_id', 'address'
            ]);

            if (isset($_FILES['avatar'])) {
                $avatar = $this->saveAvatar();
                $data['avatar'] = CommonHelper::$HOST . $avatar;
            }
            $result = $this->user->updated($this->uid, $data);
            $detail = $this->user->detail($this->uid);

            return $this->success($detail);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }

    /**
     * 修改头像
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function avatar()
    {
        $avatar = $this->saveAvatar();
        $avatar = CommonHelper::$HOST . $avatar;
        try {
            $result = $this->user->updated($this->uid, ['avatar' => $avatar]);

            return $this->success(['avatar' => $avatar]);
        } catch (ValidateException $e) {
            return $this->validateError($e);
        }
    }

    private function saveAvatar()
    {
        $fileName = $_FILES['avatar']['name'];
        $tmpName = $_FILES['avatar']['tmp_name'];
        $filePath = 'user/' . $this->uid . '/avatar/';
        if (!file_exists($filePath)) {
            CommonHelper::mkdirs($filePath);
        } else {
            array_map('unlink', glob($filePath . '*'));
        }
        $fileName = explode('.', $fileName);
        if (isset($fileName[1]) && in_array($fileName[1], ['jpg', 'png'])) {
            $avatar = $filePath . time() . '.' . $fileName[1];
            if (move_uploaded_file($tmpName, $avatar)) {
                return $avatar;
            } else {
                return $this->fail('上传失败');
            }
        } else {
            return $this->fail('头像格式错误');
        }
    }

    /**
     * 退出
     *
     * @return \Illuminate\Http\JsonResponse
     */
    public function logout()
    {
        try {
            $result = $this->user->logout($this->uid);

            return $this->success($result);
        } catch (ValidateException $e) {

            return $this->validateError($e);
        }
    }
}